Frunk
frunk frəNGk
- Functional programming toolbelt in Rust.
- Might seem funky at first, but you'll like it.
- Comes from: funktional (German) + Rust → Frunk
The general idea is to make things easier by providing FP tools in Rust to allow for stuff like this:
use combine_all;
let v = vec!;
assert_eq!;
// Slightly more magical
let t1 = ;
let t2 = ;
let t3 = ;
let tuples = vec!;
let expected = ;
assert_eq!;
For a deep dive, RustDocs are available for:
- Code on Master
- Latest published release
Table of Contents
- HList
- Generic
- 2.1 LabelledGeneric
- 2.1.2 Path (Lenses)
- 2.1 LabelledGeneric
- Coproduct
- Validated
- Semigroup
- Monoid
- Features
- Benchmarks
- Todo
- Contributing
- Inspirations
- Maintainers
Examples
HList
Statically typed heterogeneous lists.
First, let's enable hlist
:
use ;
Some basics:
let h = hlist!;
// Type annotations for HList are optional. Here we let the compiler infer it for us
// h has a static type of: HCons<i32, HNil>
// HLists have a head and tail
assert_eq!;
assert_eq!;
// You can convert a tuple to an HList and vice-versa
let h2 = hlist!;
let t: = h2.into;
assert_eq!;
let t3 = ;
let h3: HList! = t3.into;
assert_eq!;
HLists have a hlist_pat!
macro for pattern matching;
let h: HList! = hlist!;
// We use the HList! type macro to make it easier to write
// a type signature for HLists, which is a series of nested HCons
// h has an expanded static type of: HCons<&str, HCons<&str, HCons<i32, HCons<bool, HNil>>>>
let hlist_pat! = h;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// You can also use into_tuple2() to turn the hlist into a nested pair
To traverse or build lists, you can also prepend/or pop elements at the front:
let list = hlist!;
// h has a static type of: HCons<bool, HCons<&str, HCons<Option<{integer}>, HNil>>>
let = list.pop;
assert_eq!;
assert_eq!;
let list1 = tail1.prepend;
assert_eq!;
// or using macro sugar:
let hlist_pat! = list; // equivalent to pop
let list2 = hlist!; // equivalent to prepend
assert_eq!;
You can reverse, map, and fold over them too:
// Reverse
let h1 = hlist!;
assert_eq!;
// Fold (foldl and foldr exist)
let h2 = hlist!;
let folded = h2.foldr;
assert_eq!
// Map
let h3 = hlist!;
let mapped = h3.map;
assert_eq!;
You can pluck a type out of an HList
using pluck()
, which also gives you back the remainder after plucking that type
out. This method is checked at compile-time to make sure that the type you ask for can be extracted.
let h = hlist!;
let : = h.pluck;
assert!;
assert_eq!
Similarly, you can re-shape, or sculpt, an Hlist
, there is a sculpt()
method, which allows you to re-organise and/or
cull the elements by type. Like pluck()
, sculpt()
gives you back your target with the remainder data in a pair. This
method is also checked at compile time to make sure that it won't fail at runtime (the types in your requested target shape
must be a subset of the types in the original HList
.
let h = hlist!;
let : = h.sculpt;
assert_eq!;
assert_eq!;
Generic
Generic
is a way of representing a type in ... a generic way. By coding around Generic
, you can to write functions
that abstract over types and arity, but still have the ability to recover your original type afterwards. This can be a fairly powerful thing.
Setup
In order to derive the trait Generic
(or LabelledGeneric
) you will have to add frunk_core
dependency
[]
= { = "$version" }
Frunk comes out of the box with a nice custom Generic
derivation so that boilerplate is kept to a minimum.
Here are some examples:
HList ⇄ Struct
let h = hlist!;
let p: Person = from_generic;
assert_eq!;
This also works the other way too; just pass a struct to into_generic
and get its generic representation.
Converting between Structs
Sometimes you may have 2 different types that are structurally the same (e.g. different domains but the same data). Use cases include:
- You have a models for deserialising from an external API and equivalents for your app logic
- You want to represent different stages of the same data using types (see this question on StackOverflow)
Generic comes with a handy convert_from
method that helps make this painless:
// Assume we have all the imports needed
let a_person = ApiPerson ;
let d_person: DomainPerson = convert_from; // done
LabelledGeneric
In addition to Generic
, there is also LabelledGeneric
, which, as the name implies, relies on a generic representation
that is labelled. This means that if two structs derive LabelledGeneric
, you can convert between them only if their
field names match!
Here's an example:
// Suppose that again, we have different User types representing the same data
// in different stages in our application logic.
let n_user = NewUser ;
// Convert from a NewUser to a Saved using LabelledGeneric
//
// This will fail if the fields of the types converted to and from do not
// have the same names or do not line up properly :)
//
// Also note that we're using a helper method to avoid having to use universal
// function call syntax
let s_user: SavedUser = labelled_convert_from;
assert_eq!;
assert_eq!;
assert_eq!;
// Uh-oh ! last_name and first_name have been flipped!
// This would fail at compile time :)
let d_user: DeletedUser = labelled_convert_from;
// This will, however, work, because we make use of the Sculptor type-class
// to type-safely reshape the representations to align/match each other.
let d_user: DeletedUser = transform_from;
Transmogrifying
Sometimes you need might have one data type that is "similar in shape" to another data type, but it
is similar recursively (e.g. it has fields that are structs that have fields that are a superset of
the fields in the target type, so they are transformable recursively). .transform_from
can't help you
there because it doesn't deal with recursion, but the Transmogrifier
can help if both are LabelledGeneric
by transmogrify()
ing from one to the other.
What is "transmogrifying"? In this context, it means to recursively tranform some data of type A into data of type B, in a typesafe way, as long as A and B are "similarly-shaped". In other words, as long as B's fields and their subfields are subsets of A's fields and their respective subfields, then A can be turned into B.
As usual, the goal with Frunk is to do this:
- Using stable (so no specialisation, which would have been helpful, methinks)
- Typesafe
- No usage of
unsafe
Here is an example:
use Transmogrifier;
let internal_user = InternalUser ;
/// Boilerplate-free conversion of a top-level InternalUser into an
/// ExternalUser, taking care of subfield conversions as well.
let external_user: ExternalUser = internal_user.transmogrify;
let expected_external_user = ExternalUser ;
assert_eq!;
Note that as of writing, there are a couple of known limitations with transmogrify()
,
some of which may be addressed in the future:
- If one of the fields is an identical type and derives
LabelledGeneric
, the compiler will tell you that it can't "infer an index" fortransmogrify()
; this is becauseimpl
s of theTransmogrifier
trait will clash. This may or may not change in the future (perhaps if we move to a pure procedural macro powered way of doing things?) - For types that contain many multiple deeply-nested fields that require
transmogfiy()
ing, using this technique will likely increase your compile time. - If you've balked at the the compile-time errors with
transform_from
when a transform is deemed impossible (e.g. missing field), the errors fortransmogrify()
are worse to the degree that recursivetransmogrify()
is required for your types.
For more information how Generic and Field work, check out their respective Rustdocs:
Path
One of the other things that LabelledGeneric
-deriving structs can do is be generically traversed
using Path
and its companion trait PathTraverser
. In some circles, this functionality is also
called a Lens.
Path
-based traversals are
- Easy to use through the procedural macro
path!
(frunk_proc_macros
)- Traversing multiple levels is familiar; just use dot
.
syntax (path!(nested.attribute.value)
)
- Traversing multiple levels is familiar; just use dot
- Compile-time safe
- Composable (add one to the other using
+
) - Allows you to get by value, get by reference or get by mutable reference, depending on the type of thing you pass it.
let mut dog = Dog ;
let cat = Cat ;
// generic, re-usable, compsable paths
let dimensions_lens = path!;
let height_lens = dimensions_lens + path!; // compose multiple
let unit_lens = path!; // dot syntax to just do the whole thing at once
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// modify by passing a &mut
*height_lens.get = 13;
assert_eq!;
There's also a Path!
type-level macro for declaring shape-constraints. This allows you to write adhoc shape-dependent
functions for LabelledGeneric
types.
// Prints height as long as `A` has the right "shape" (e.g.
// has `dimensions.height: usize` and `dimension.unit: SizeUnit)
See examples/paths.rs
to see how this works.
Coproduct
If you've ever wanted to have an adhoc union / sum type of types that you do not control, you may want
to take a look at Coproduct
. In Rust, thanks to enum
, you could potentially declare one every time you
want a sum type to do this, but there is a light-weight way of doing it through Frunk:
use *; // for the fold method
// Declare the types we want in our Coproduct
type I32F32Bool = Coprod!;
let co1 = inject;
let get_from_1a: = co1.get;
let get_from_1b: = co1.get;
assert_eq!;
// None because co1 does not contain a bool, it contains an i32
assert_eq!;
// This will fail at compile time because i8 is not in our Coproduct type
let nope_get_from_1b: = co1.get; // <-- will fail
// It's also impossible to inject something into a coproduct that is of the wrong type
// (not contained in the coproduct type)
let nope_co = inject; // <-- will fail
// We can fold our Coproduct into a single value by handling all types in it
assert_eq!;
For more information, check out the docs for Coproduct
Validated
Validated
is a way of running a bunch of operations that can go wrong (for example,
functions returning Result<T, E>
) and, in the case of one or more things going wrong,
having all the errors returned to you all at once. In the case that everything went well, you get
an HList
of all your results.
Mapping (and otherwise working with plain) Result
s is different because it will
stop at the first error, which can be annoying in the very common case (outlined
best by the Cats project).
To use Validated
, first:
use *; // for Result::into_validated
Assuming we have a Person
struct defined
Here is an example of how it can be used in the case that everything goes smoothly.
// Build up a `Validated` by adding in any number of `Result`s
let validation = get_name.into_validated + get_age + get_street;
// When needed, turn the `Validated` back into a Result and map as usual
let try_person = validation.into_result
// Destructure our hlist
.map;
assert_eq! );
}
If, on the other hand, our Result
s are faulty:
/// This next pair of functions always return Recover::Err
let validation2 = get_name_faulty.into_validated + get_age_faulty;
let try_person2 = validation2.into_result
.map;
// Notice that we have an accumulated list of errors!
assert_eq!;
Semigroup
Things that can be combined.
use Semigroup;
use All;
assert_eq!;
assert_eq!; // bit-wise &&
assert_eq!;
Monoid
Things that can be combined and have an empty/id value.
use combine_all;
let t1 = ;
let t2 = ;
let t3 = ;
let tuples = vec!;
let expected = ;
assert_eq!
let product_nums = vec!;
assert_eq!
Features
Frunk comes with support for deriving serde serializer/deserializers for its core
data structures. This can be enabled by adding the serde
feature flag.
For example, if you'd like to use just frunk_core
with serde
[]
= { = "$version", = ["serde"] }
Or, if you'd like to use frunk
with serde, you need to explicitly include frunk_core
as well
[]
= { = "$version", = ["serde"] }
= { = "$version", = ["serde"] }
Benchmarks
Benchmarks are available in ./benches
and can be run with:
$ rustup run nightly cargo bench
Benchmarks on master
are also auto-generated, uploaded and available online.
Todo
Stabilise interface, general cleanup
Before a 1.0 release, would be best to revisit the design of the interfaces and do some general code (and test cleanup).
Not yet implemented
Given that Rust has no support for Higher Kinded Types, I'm not sure if these
are even possible to implement. In addition, Rustaceans are used to calling iter()
on collections to get a lazy view, manipulating their elements with map
or and_then
, and then doing a collect()
at the end to keep things
efficient. The usefulness of these following structures maybe limited in that context.
Functor
Monad
Apply
Applicative
Contributing
Yes please !
The following are considered important, in keeping with the spirit of Rust and functional programming:
- Safety (type and memory)
- Efficiency
- Correctness
Inspirations
Scalaz, Shapeless, Cats, Haskell, the usual suspects ;)
Maintainers
A.k.a. people whom you can bug/tag/@ on Gitter :D